package com.uottawa.library.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.uottawa.library.domain.Title;

public class TitleDAO extends BaseDAO {

	public boolean addTitle(Title title) {
		String query = "INSERT INTO TITLE VALUES ('" + title.getIsbn() + "', '" + title.getName() + "')"; 
		Connection connection = getConnection();
		try {
			Statement stmt = connection.createStatement();
			stmt.execute(query);
		} catch (SQLException e) {
			return false;
		} finally {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return true;
	}

	public boolean RemoveTitle(int isbn) {
		String query = "DELETE FROM TITLE WHERE ISBN =" + isbn; 
		Connection connection = getConnection();
		try {
			Statement stmt = connection.createStatement();
			stmt.execute(query);
		} catch (SQLException e) {
			return false;
		} finally {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return true;
	}

	public List<Title> getAllTitles() {
		List<Title> result = new ArrayList<Title>();
		
		String query = "SELECT * FROM TITLE" ; 
		Connection connection = getConnection();
		try {
			PreparedStatement stmt = connection.prepareStatement(query);
			ResultSet rs = stmt.executeQuery(query);
			if(rs !=null)
			{
				while(rs.next()) {
					Title title = new Title(rs.getInt("ISBN"));
					title.setName(rs.getString("NAME"));
					result.add(title);
				}
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return result;
	}

	public boolean updateTitle(int isbn, String name) {
		String query = "UPDATE  TITLE SET NAME='" + name + "' WHERE ISBN = " + isbn; 
		Connection connection = getConnection();
		try {
			Statement stmt = connection.createStatement();
			stmt.execute(query);
		} catch (SQLException e) {
			return false;
		} finally {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return true;
	}
	
}
